package com.moyu.gateway.interfaceimpl;

/**
 * @Author 赵彦博
 * @Date 2024/11/29 19:55
 */

import cn.dev33.satoken.stp.StpInterface;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 自定义权限验证接口扩展,在需要鉴权时自动调用
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 本list仅做模拟，实际项目中要根据具体业务逻辑来查询权限
        List<String> list = new ArrayList<>();
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select distinct c.router_name\n" +
                "from tb_user_role a\n" +
                "left join tb_role_permission b on a.role_id = b.role_id\n" +
                "left join tb_permission c on c.id = b.permission_id\n" +
                "where a.user_id = ?", loginId);
        for (Map<String, Object> map : maps) {
            list.add(map.get("router_name").toString());
        }
        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 本list仅做模拟，实际项目中要根据具体业务逻辑来查询角色
        List<String> list = new ArrayList<>();
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select distinct b.name\n" +
                "from tb_user_role a\n" +
                "left join tb_role b on a.role_id = b.id\n" +
                "where a.user_id = ?", loginId);
        for (Map<String, Object> map : maps) {
            list.add(map.get("name").toString());
        }
        return list;
    }
}
